<script setup lang="ts">
import type { OptionsType } from "@/components/ReSegmented";
import Segmented from "@/components/ReSegmented";
import {
  GridComponent,
  LegendComponent,
  TooltipComponent
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import { OrderStatsItem } from "types/order";
import { getOrderStats } from "@/api/order";
import { LineChart } from "echarts/charts";
import { onMounted, ref } from "vue";
import { use } from "echarts/core";
import VChart from "vue-echarts";
import dayjs from "dayjs";
import numeral from "numeral";
import { CustomerStatsItem } from "types/customer";
import { getCustomerStats } from "@/api/customer";

use([
  GridComponent,
  LegendComponent,
  TooltipComponent,
  LineChart,
  CanvasRenderer
]);

const curWeek = ref(1);
const optionsBasis: Array<OptionsType> = [
  {
    label: "上周",
    value: 0
  },
  {
    label: "本周",
    value: 1
  }
];

const option = ref({
  xAxis: {
    type: "category",
    // show: false,
    data: []
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  },
  grid: {
    // top: "12px",
    bottom: "36px",
    left: "60px",
    right: 0
  },
  yAxis: {
    // show: false,
    type: "value"
  },
  legend: {
    data: ["销售额", "订单量", "新增客户"]
  },
  series: [
    {
      name: "销售额",
      data: [],
      type: "line",
      symbol: "none",
      smooth: true,
      color: "#41b6ff",
      lineStyle: {
        shadowOffsetY: 3,
        shadowBlur: 7,
        shadowColor: "#41b6ff"
      }
    },
    {
      name: "订单量",
      data: [],
      type: "line",
      symbol: "none",
      smooth: true,
      color: "#e85f33",
      lineStyle: {
        shadowOffsetY: 3,
        shadowBlur: 7,
        shadowColor: "#e85f33"
      }
    },
    {
      name: "新增客户",
      data: [],
      type: "line",
      symbol: "none",
      smooth: true,
      color: "#26ce83",
      lineStyle: {
        shadowOffsetY: 3,
        shadowBlur: 7,
        shadowColor: "#26ce83"
      }
    }
  ]
});

const orderData = ref<OrderStatsItem[]>([]);
const customerData = ref<CustomerStatsItem[]>([]);

const renderChart = async () => {
  try {
    orderData.value = await getOrderStats();
    customerData.value = await getCustomerStats();

    let start = dayjs().startOf("week");
    let end = dayjs().endOf("week");

    if (curWeek.value) {
      start = dayjs().startOf("week");
      end = dayjs().endOf("week");
    } else {
      start = dayjs().subtract(1, "week").startOf("week");
      end = dayjs().subtract(1, "week").endOf("week");
    }

    const dataMap: Record<
      string,
      {
        order: number;
        sales: number;
        customer: number;
      }
    > = {};

    while (start <= end) {
      dataMap[start.format("YYYY-MM-DD")] = {
        order: 0,
        sales: 0,
        customer: 0
      };
      start = start.add(1, "d");
    }

    orderData.value.forEach(item => {
      const key = dayjs(item.created_on).format("YYYY-MM-DD");
      if (dataMap[key] !== undefined) {
        dataMap[key].order += 1;
        dataMap[key].sales =
          numeral(dataMap[key].sales).add(item.total_price).value() ?? 0;
      }
    });

    customerData.value.forEach(item => {
      const key = dayjs(item.created_on).format("YYYY-MM-DD");
      if (dataMap[key] !== undefined) {
        dataMap[key].customer += 1;
      }
    });

    option.value.xAxis.data = Object.keys(dataMap).map(date =>
      dayjs(date, "YYYY-MM-DD").format("dddd")
    );

    option.value.series[0].data = Object.values(dataMap).map(
      item => item.sales
    );

    option.value.series[1].data = Object.values(dataMap).map(
      item => item.order
    );

    option.value.series[2].data = Object.values(dataMap).map(
      item => item.customer
    );
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  renderChart();
});
</script>
<template>
  <el-card class="bar-card" shadow="never">
    <div class="flex justify-between">
      <span class="text-md font-medium">分析概览</span>
      <Segmented
        v-model="curWeek"
        :options="optionsBasis"
        @change="renderChart"
      />
    </div>
    <div class="flex justify-between items-start mt-3">
      <v-chart :option="option" autoresize style="width: 100%; height: 365px" />
    </div>
  </el-card>
</template>
